package com.qixin.api.serviceimpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qixin.api.bean.*;
import com.qixin.api.mapper.ComPtUserMapper;
import com.qixin.api.service.*;
import com.qixin.util.cache.EhcacheUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 企业用户表 服务实现类
 * </p>
 *
 * @author 吕正睿
 * @since 2018-10-28
 */
@Service
public class ComPtUserServiceImpl extends ServiceImpl<ComPtUserMapper, ComPtUser> implements ComPtUserService {
	private static final Logger logger = LoggerFactory.getLogger(ComPtUserServiceImpl.class);
    @Autowired
    ComLicenseFileService comLicenseFileService;
	@Autowired
	ComMoneyInfoService comMoneyInfoService;
@Autowired
PtMenuResourseService ptMenuResourseService;
@Autowired
PtRoleUserService ptRoleUserService;
    @Override
    public boolean login(ComPtUser comPtUser, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_name", comPtUser.getUserName());
        map.put("pass_word", comPtUser.getPassWord());
        List<ComPtUser> comPtUsers = baseMapper.login(map);
        //如果用户存在，放入session域
        if (comPtUsers.size() > 0) {
//			comPtUsers.get(0).getPtRole().setPtMenuResourses(ptMenuResourseService.findMenuByRole(comPtUsers.get(0).getPtRole()));
            session.setAttribute("user", comPtUsers.get(0));
            session.setAttribute("flag", comPtUsers.get(0).getFlag());

            return true;
        } else {
            return false;
        }
    }


    @Override
    public ResultPage<ComPtUser> selectALL(VoPage voPage) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        List<ComPtUser> list = baseMapper.selectALL(paramMap);
        Integer count = baseMapper.countMyPage2(paramMap);
        ResultPage<ComPtUser> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

	@Override
	public boolean addmoney(HttpSession session, Double moeny,Long peopleId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("username",((ComUser)session.getAttribute("user")).getCallPhone());
		paramMap.put("money",moeny);
		paramMap.put("peopleId",peopleId);
		Integer addmoney=baseMapper.addmoney(paramMap);
		if (addmoney==null){
			ComMoneyInfo comMoneyInfo=new ComMoneyInfo();
			SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String datetime = tempDate.format(new java.util.Date());
			comMoneyInfo.setCreatTime(datetime);
			comMoneyInfo.setAddmoney(moeny);
			comMoneyInfo.setToeleUserName(((ComUser)session.getAttribute("user")).getCallPhone());
			comMoneyInfo.setPtId(peopleId);
			comMoneyInfo.setOffmoney(0.0);
			comMoneyInfoService.insert(comMoneyInfo);
			return true;
		}
		return  false;
	}

	@Override
	public boolean offmoney(HttpSession session, Double moeny,Long peopleId) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("username",((ComUser)session.getAttribute("user")).getCallPhone());
		paramMap.put("money",moeny);
		paramMap.put("peopleId",peopleId);
		Integer offmoney=baseMapper.offmoney(paramMap);
		if (offmoney==null){
			ComMoneyInfo comMoneyInfo=new ComMoneyInfo();
			SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String datetime = tempDate.format(new java.util.Date());
			comMoneyInfo.setCreatTime(datetime);
			comMoneyInfo.setAddmoney(0.0);
			comMoneyInfo.setToeleUserName(((ComUser)session.getAttribute("user")).getCallPhone());
			comMoneyInfo.setPtId(peopleId);
			comMoneyInfo.setOffmoney(moeny);
			comMoneyInfoService.insert(comMoneyInfo);
			return true;
		}
		return  false;
	}
	@Override
    public ResultPage<ComPtUser> selectphone(VoPage voPage, Long phone) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        paramMap.put("phone", phone);
        List<ComPtUser> list = baseMapper.selectphone(paramMap);
        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<ComPtUser> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

	@Override
	public ResultPage<ComPtUser> selectMyPage(VoPage voPage, HttpSession session, ComPtUser comPtUser) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
		paramMap.put("limit", voPage.getLimit());
		List<ComPtUser> list = baseMapper.selectcompany(paramMap,comPtUser);
		Integer count = baseMapper.countMyPage(paramMap);
		ResultPage<ComPtUser> resultPage = new ResultPage<>();
		resultPage.setCode(0);
		resultPage.setCount(count);
		resultPage.setMsg("成功");
		resultPage.setData(list);
		return resultPage;
	}

	@Override
    public boolean update(ComPtUser comPtUser, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_name", comPtUser.getUserName());
        map.put("pass_word", comPtUser.getPassWord());
        List<ComPtUser> comPtUsers = baseMapper.login(map);
        boolean flag = false;
        if (comPtUsers.size() > 0) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("user_name", comPtUser.getUserName());
            paramMap.put("newpassword1", comPtUser.getNewpassword1());
            Integer password = baseMapper.updatepassword(paramMap);
            if (password == null) {
                flag = true;
            } else flag = false;
        }
        return flag;

    }

    @Override
    public int sepeople(Long id) {
        int num = baseMapper.sepeople(id);

        return num;
    }

    @Override
    public int chargenum(Long id) {
        int chargenum = baseMapper.chargenum(id);

        return chargenum;
    }

    @Override
    public long carnum(String ptname) {
        long carnum = baseMapper.carnum(ptname);

        return carnum;
    }

    @Override
    public String checkup(ComPtUser comPtUser, Long[] filesId) throws SQLException {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        this.updateById(comPtUser);
        if (filesId!=null){
        for (int i = 0; i < filesId.length; i++) {
            ComLicenseFile comLicenseFile = new ComLicenseFile();
            comLicenseFile.setId(filesId[i]);
            comLicenseFile.setRelactionId(comPtUser.getId());
            if (!comLicenseFileService.updateById(comLicenseFile)) {
                throw new SQLException();
            }

        }}
        jsonMap.put("flag",true);
        jsonMap.put("msg", "保存成功");
        return JSON.toJSONString(jsonMap);
    }
//获取企业营业执照路径
    @Override
    public String license(Long id) {
        String license = baseMapper.license(id);

        return license;
    }

    @Override
    public int mov(Long id) {
    return    baseMapper.mov(id);

    }






	//给车辆分配资金之后更改企业余额
	@Override
	public int updatepartgivemoney(PtMoneyInfo ptMoneyInfo) {

		return baseMapper.updatepartgivemoney(ptMoneyInfo);
	}

	@Override
	public int updatepartremovemoney(PtMoneyInfo ptMoneyInfo) {
		return baseMapper.updatepartremovemoney(ptMoneyInfo);
	}

	@Override
    public ComPtUser findUserInfoByUserIdForWeChart(Long userId) {
        return baseMapper.findUserInfoByUserIdForWeChart(userId);
    }

    @Override
    public ComPtUser findUserInfoByPtUserIdForWeChart(Long userId) {
        return baseMapper.findUserInfoByPtUserIdForWeChart(userId);
    }

	@Override
	public String updatept(String param, String code) {
		ComPtUser comPtUser=  JSONObject.parseObject(param,ComPtUser.class);
		if(!equalsCache(code,comPtUser.getCallPhone())){

			return  "验证码错误";
		}
		comPtUser.setUserName(comPtUser.getCallPhone());
		comPtUser.setPassWord(comPtUser.getPassWord());
		if (baseMapper.updatept(comPtUser)>=0){
			return "修改成功";
		}
		else {
			return "无该企业账户";
		}


	}

	public boolean equalsCache(String code,String phone) {

		//从缓存中获取六位验证码 当访问过一次后 60秒内没有再此访问会过期  缓存区的key设置成数字加字符串 否则获取不到
		String cacheCode= EhcacheUtil.get("SMS",phone+"Data")+"";
		logger.info("缓存中的验证码："+cacheCode);
		logger.info("用户输入的验证码："+code);
		logger.info("用户手机号："+phone);
		if (code.equals(cacheCode)){
			return true;
		}
		return false;
	}
}